package com.sarnath.sardoop.modules.hadoop.util;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.sarnath.sardoop.modules.hadoop.service.HdfsExplorerService;


@Service("byteClassLoader")
@Lazy(false)
public class ByteClassLoader extends ClassLoader {
	private static Map<String, URLClassLoader> jarMap=new HashMap<>();
	@Resource
	private HdfsExplorerService hdfsExplorer;
	
	public Class<?> loadClass(String path,String name) throws Exception{
		URLClassLoader loader=jarMap.get(path);
		if(loader==null){
			byte[] jarBytes=hdfsExplorer.download(path);
			File f=File.createTempFile("jar", "jar");
			try(FileOutputStream fileOutputStream = new FileOutputStream(f)) {
				IOUtils.write(jarBytes, fileOutputStream);
			}
			loader=URLClassLoader.newInstance(new URL[]{new URL("file:"+f.getAbsolutePath())},this.getClass().getClassLoader());
		}
		return loader.loadClass(name);
	}
}
